package com.futvan.z.framework.util;

import java.io.File;
import java.util.Date;
import java.util.HashMap;
import java.util.Properties;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.Address;
import javax.mail.Authenticator;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.internet.MimeUtility;

import com.futvan.z.framework.common.bean.Code;
import com.futvan.z.framework.common.bean.Result;
import com.futvan.z.framework.core.z;

/**
 * 邮件工具类
 * @author zz
 *
 */
public class EmailUtil {
	
	
	
	/**
	 * 发送邮件
	 * @param address 收件人邮箱
	 * @param title 邮件标题
	 * @param info 邮件正文
	 * @param file 附件
	 * @return
	 */
	public static Result sent(String address, String title, String info,String filepath) {
		Result result = new Result();
		MailSenderInfo mail = new MailSenderInfo();
		String email_smtp = "smtp.qq.com";
		String email_port = "465";
		String email_username = "1430856243";
		String email_password = "keudtuzbvxuejajd";
		String email_fromaddress = "1430856243@qq.com";

		if ("".equals(address) || address == null) {
			result.setCode(Code.ERROR);
			result.setMsg("收件邮箱地址为空");
		} else if ("".equals(title) || title == null) {
			result.setCode(Code.ERROR);
			result.setMsg("标题为空");
		} else if ("".equals(info) || info == null) {
			result.setCode(Code.ERROR);
			result.setMsg("内容为空");
		} else if ("".equals(email_smtp) || email_smtp == null) {
			result.setCode(Code.ERROR);
			result.setMsg("系统邮箱SMTP地址为空");
		} else if ("".equals(email_port) || email_port == null) {
			result.setCode(Code.ERROR);
			result.setMsg("系统邮箱端口为空");
		} else if ("".equals(email_username) || email_username == null) {
			result.setCode(Code.ERROR);
			result.setMsg("系统邮箱账号为空");
		} else if ("".equals(email_password) || email_password == null) {
			result.setCode(Code.ERROR);
			result.setMsg("系统邮箱密码为空");
		} else if ("".equals(email_fromaddress) || email_fromaddress == null) {
			result.setCode(Code.ERROR);
			result.setMsg("系统邮箱地址为空");
		}else {
			mail.setMailServerHost(email_smtp);
			mail.setMailServerPort(email_port);
			// 登录账号
			mail.setUserName(email_username);
			// 登录密码
			mail.setPassword(email_password);
			// 发送邮箱
			mail.setFromAddress(email_fromaddress);
			// 收件人
			mail.setToAddress(address);
			// 标题
			mail.setSubject(title);
			// 内容
			mail.setContent(info);
			//附件
			if(z.isNotNull(filepath)) {
				String[]files = new String[1]; 
				files[0] = filepath;
				mail.setAttachFileNames(files);
			}
			
			// 发送
			boolean sentstate = sent(mail);
			if(sentstate) {
				result.setCode(Code.SUCCESS);
				result.setMsg("发送成功");
			}else {
				result.setCode(Code.ERROR);
				result.setMsg("邮件发送出错");
			}
		}
		return result;
	}
	
	/**
	 * 发送邮件
	 * @param address 收件人邮箱
	 * @param title 邮件标题
	 * @param info 邮件正文
	 * @param file 附件
	 * @return
	 */
	public static Result sent(String address, String title, String info) {
		return sent(address,title,info,null);
	}

	/**
	 * 发送邮件
	 * 
	 * @param mailInfo
	 * @return
	 * @author zhaojian
	 * @Email 4223947@qq.com
	 * @CreateTime 2017-11-14 11:14:12
	 * 
	 * 
	 * 
	 *             //调用实例 MailSenderInfo mail = new MailSenderInfo();
	 *             mail.setMailServerHost("smtp.163.com");
	 *             mail.setMailServerPort("25"); //登录账号
	 *             mail.setUserName("futvan"); //登录密码
	 *             mail.setPassword("findent12517"); //发送邮箱
	 *             mail.setFromAddress("futvan@163.com"); //收件人
	 *             mail.setToAddress("4223947@qq.com"); //标题
	 *             mail.setSubject("测试邮件"); //内容 mail.setContent("这是一封测试邮件！");
	 *             //附件 String[]file = new String[1]; file[0] = "D:/桌面.jpg";
	 *             mail.setAttachFileNames(file);
	 * 
	 *             //发送 sent(mail);
	 */
	public static boolean sent(MailSenderInfo mailInfo) {
		boolean result = false;
		// 判断是否需要身份认证
		MyAuthenticator authenticator = null;
		Properties pro = mailInfo.getProperties();
		// 如果需要身份认证，则创建一个密码验证器
		if (mailInfo.isValidate()) {
			authenticator = new MyAuthenticator(mailInfo.getUserName(),mailInfo.getPassword());
		}
		// 根据邮件会话属性和密码验证器构造一个发送邮件的session
		Session sendMailSession = Session.getDefaultInstance(pro, authenticator);
		try {
			// 根据session创建一个邮件消息
			Message mailMessage = new MimeMessage(sendMailSession);
			// 创建邮件发送者地址
			Address from = new InternetAddress(mailInfo.getFromAddress());
			// 设置邮件消息的发送者
			mailMessage.setFrom(from);
			// 创建邮件的接收者地址，并设置到邮件消息中
			String ToAddress = mailInfo.getToAddress();
			Address[] to = new Address[ToAddress.split(",").length];
			for (int i = 0; i < ToAddress.split(",").length; i++) {
				to[i] = new InternetAddress(ToAddress.split(",")[i]);
			}
			// Message.RecipientType.TO属性表示接收者的类型为TO
			mailMessage.setRecipients(Message.RecipientType.TO, to);
			// 设置邮件消息的主题
			mailMessage.setSubject(mailInfo.getSubject());
			// 设置邮件消息发送的时间
			mailMessage.setSentDate(new Date());
			// MiniMultipart类是一个容器类，包含MimeBodyPart类型的对象
			Multipart mainPart = new MimeMultipart();
			// 创建一个包含HTML内容的MimeBodyPart
			BodyPart html = new MimeBodyPart();
			// 设置HTML内容
			html.setContent(mailInfo.getContent(), "text/html; charset=utf-8");
			mainPart.addBodyPart(html);
			// 添加附件enclosure
			if (mailInfo.getAttachFileNames() != null) {
				for (int i = 0; i < mailInfo.getAttachFileNames().length; i++) {
					BodyPart FJ = new MimeBodyPart();
					FileDataSource fds = new FileDataSource(
							mailInfo.getAttachFileNames()[i]);
					FJ.setDataHandler(new DataHandler(fds)); // 得到附件本身并至入BodyPart
					FJ.setFileName(MimeUtility.encodeText(fds.getName()));
					mainPart.addBodyPart(FJ);
				}
			}

			// 将MiniMultipart对象设置为邮件内容
			mailMessage.setContent(mainPart);
			Transport transport = sendMailSession.getTransport("smtp");
			transport.connect(mailInfo.getMailServerHost(),mailInfo.getUserName(), mailInfo.getPassword());
			// 发送邮件
			transport.sendMessage(mailMessage, mailMessage.getAllRecipients());
			// 关闭连接
			transport.close();
			result = true;
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		return result;
	}

	/**
	 * 判断发送端服务器连接状态
	 * 
	 * @return
	 * 
	 * 
	 *         //调用实例 MailSenderInfo mail = new MailSenderInfo(); //pop地址
	 *         mail.setMailServerPOPHost("pop.163.com"); //smtp地址
	 *         mail.setMailServerHost("smtp.163.com"); //发送端口
	 *         mail.setMailServerPort("25"); //登录账号 mail.setUserName("futvan");
	 *         //登录密码 mail.setPassword("findent12517");
	 * 
	 *         boolean tt = getServerStatus(mail); System.out.println(tt);
	 */
	//	public static boolean getServerStatus(MailSenderInfo mailInfo) {
	//		try {
	//			Properties pro = mailInfo.getProperties();
	//			MyAuthenticator authenticator = authenticator = new MyAuthenticator(
	//					mailInfo.getUserName(), mailInfo.getPassword());
	//			Session sendMailSession = Session.getDefaultInstance(pro,
	//					authenticator);
	//			Store store = sendMailSession.getStore("pop3");
	//			store.connect(mailInfo.getMailServerPOPHost(),
	//					mailInfo.getUserName(), mailInfo.getPassword());
	//			return true;
	//		} catch (Exception e) {
	//			return false;
	//		}
	//	}

}

class MailSenderInfo {

	// 发送邮件的服务器的IP和端口
	private String mailServerHost;
	private String mailServerPOPHost;
	private String mailServerPort;
	// 邮件发送者的地址
	private String fromAddress;
	// 邮件接收者的地址
	private String toAddress;
	// 登陆邮件发送服务器的用户名和密码
	private String userName;
	private String password;
	// 是否需要身份验证
	private boolean validate = true;
	// 邮件主题
	private String subject;
	// 邮件的文本内容
	private String content;
	// 邮件附件的文件名
	private String[] attachFileNames;

	/**
	 * 获得邮件会话属性
	 */
	public Properties getProperties() {
		Properties p = new Properties();
		p.put("mail.smtp.host", this.mailServerHost);
		p.put("mail.smtp.port", this.mailServerPort);
		p.put("mail.smtp.auth", validate ? "true" : "false");

		// 开启SSL加密
		p.put("mail.smtp.ssl.enable", "true");
		p.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
		p.put("mail.smtp.socketFactory.fallback", "false");
		p.put("mail.smtp.socketFactory.port", this.mailServerPort);

		return p;
	}

	public String getMailServerHost() {
		return mailServerHost;
	}

	public void setMailServerHost(String mailServerHost) {
		this.mailServerHost = mailServerHost;
	}

	public String getMailServerPort() {
		return mailServerPort;
	}

	public void setMailServerPort(String mailServerPort) {
		this.mailServerPort = mailServerPort;
	}

	public boolean isValidate() {
		return validate;
	}

	public void setValidate(boolean validate) {
		this.validate = validate;
	}

	public String[] getAttachFileNames() {
		return attachFileNames;
	}

	public void setAttachFileNames(String[] fileNames) {
		this.attachFileNames = fileNames;
	}

	public String getFromAddress() {
		return fromAddress;
	}

	public void setFromAddress(String fromAddress) {
		this.fromAddress = fromAddress;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String getToAddress() {
		return toAddress;
	}

	public void setToAddress(String toAddress) {
		this.toAddress = toAddress;
	}

	public String getUserName() {
		return userName;
	}

	public void setUserName(String userName) {
		this.userName = userName;
	}

	public String getSubject() {
		return subject;
	}

	public void setSubject(String subject) {
		this.subject = subject;
	}

	public String getContent() {
		return content;
	}

	public void setContent(String textContent) {
		this.content = textContent;
	}

	/**
	 * @return the mailServerPOPHost
	 */
	public String getMailServerPOPHost() {
		return mailServerPOPHost;
	}

	/**
	 * @param mailServerPOPHost
	 *            the mailServerPOPHost to set
	 */
	public void setMailServerPOPHost(String mailServerPOPHost) {
		this.mailServerPOPHost = mailServerPOPHost;
	}

}

class MyAuthenticator extends Authenticator {
	String userName = null;
	String password = null;

	public MyAuthenticator() {
	}

	public MyAuthenticator(String username, String password) {
		this.userName = username;
		this.password = password;
	}

	protected PasswordAuthentication getPasswordAuthentication() {
		return new PasswordAuthentication(userName, password);
	}
}